
package com.wondertek.mist.plugins;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.LinearLayout;
import android.widget.TimePicker;

import com.wondertek.mist.utils.RUtil;


public class DateTimePickerPlugin extends CordovaPlugin {

	

	static String TAG = "SelectWidgetPlugin";
	
    @Override
	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
		
		return this.show(args, callbackContext);
	}

	public synchronized boolean show(final JSONArray data, final CallbackContext callbackContext) {
		
		final Activity currentCtx = cordova.getActivity();
		final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String action="date";
		final Calendar cal=Calendar.getInstance();
	    String title="选择时间";
		try {
			JSONObject obj = data.getJSONObject(0);
			action = obj.getString("mode");
            title=obj.getString("title");
			String datetime = obj.getString("datetime");
            if(datetime!=null){
            	
            	cal.setTimeInMillis(format.parse(datetime).getTime());
            }

		} catch (Exception e) {
			e.printStackTrace();
		}
        final String dialogTitle=title;
		
        Runnable runnable=null;
		if ("time".equalsIgnoreCase(action)) {
			runnable = new Runnable() {
				public void run() {
					TimePickerDialog timeDialog = new TimePickerDialog(currentCtx, new OnTimeSetListener(){

						@Override
						public void onTimeSet(final TimePicker view, final int hourOfDay, final int minute) {
							cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
							cal.set(Calendar.MINUTE, minute);
							callbackContext.success(format.format(cal.getTime()));
							
						}
						
					}, cal.get(Calendar.HOUR_OF_DAY),cal.get(Calendar.MINUTE), true);
					timeDialog.setTitle(dialogTitle);
					
					timeDialog.show();
				}
			};

		} else if ("date".equalsIgnoreCase(action)) {
			runnable = new Runnable() {
				public void run() {
					final DatePickerDialog dateDialog = new DatePickerDialog(currentCtx, new OnDateSetListener(){

						@Override
						public void onDateSet(final DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
							String returnDate = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
							cal.set(Calendar.YEAR, year);
							cal.set(Calendar.MONTH, monthOfYear);
							cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
							callbackContext.success(format.format(cal.getTime()));
							callbackContext.success(returnDate);
						}
						
					},cal.get(Calendar.YEAR),cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
					dateDialog.setTitle(dialogTitle);
					dateDialog.show();
				}
			};

		} else if ("datetime".equalsIgnoreCase(action)) {
			runnable = new Runnable() {
				public void run() {
					Context context=DateTimePickerPlugin.this.cordova.getActivity();
					LinearLayout dateTimeLayout  = (LinearLayout) currentCtx.getLayoutInflater().inflate(RUtil.layout(context,"datetime"), null);

					final DatePicker datePicker = (DatePicker) dateTimeLayout.findViewById(RUtil.id(context,"datepicker"));
					final TimePicker timePicker = (TimePicker) dateTimeLayout.findViewById(RUtil.id(context,"timepicker"));
					
					
					datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH), new OnDateChangedListener(){

						@Override
						public void onDateChanged(DatePicker arg0, int arg1,int arg2, int arg3) {
							//prevent to change title
						}
						
					});
					timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
                    timePicker.setCurrentMinute(cal.get(Calendar.MINUTE));
                    timePicker.setIs24HourView(true);
                    
                    AlertDialog.Builder builder= new AlertDialog.Builder(currentCtx);
                    builder.setTitle(dialogTitle);
                    builder.setView(dateTimeLayout);
                    builder.setPositiveButton("设置",new DialogInterface.OnClickListener(){
                           public void onClick(DialogInterface dialog,int whichButton){
                        	     cal.set(datePicker.getYear(), 
                        	    		      datePicker.getMonth(),
                        	    		      datePicker.getDayOfMonth(),
                        	    		      timePicker.getCurrentHour(),
                                              timePicker.getCurrentMinute());

                        	     String dateTime=format.format(cal.getTime());
                        	     callbackContext.success(dateTime);
                           }

                    });
                    builder.setNegativeButton("取消",new DialogInterface.OnClickListener(){

                           public void onClick(DialogInterface dialog,int whichButton){

                           }

                     });
                    AlertDialog dialog = builder.create();
    		    	
    		    	dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
    		    	dialog.show();

					
				}
			};
		}
		if(runnable!=null)
            cordova.getActivity().runOnUiThread(runnable);
		return true;
	}

}
